<template>
  <el-header height="60px">
    <div class="header-left">
      <!-- 跳转到http://localhost:13411/teacher/dashboard -->
      <h1 @click="goToDashboard" style="cursor: pointer;">在线考试系统 - 教师控制台</h1>
    </div>
    <div class="header-right">
      <el-dropdown>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goToDashboard">控制台首页</el-dropdown-item>
            <el-dropdown-item @click="handleChangePassword">修改密码</el-dropdown-item>
            <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
        <el-button type="primary">
          {{ userInfo.username }} - {{ userInfo.roleName }}
          <el-icon>
            <ArrowDown />
          </el-icon>
        </el-button>
      </el-dropdown>
    </div>
  </el-header>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()
const userInfo = ref({ username: '', roleId: '', roleName: '' })

onMounted(() => {
  // 从本地存储获取用户信息
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
})

const goToDashboard = () => {
  router.push('/teacher/dashboard')
}

const handleLogout = async () => {
  try {
    // 调用后端登出接口，带上cookie
    await fetch('/user/logout', { method: 'POST', credentials: 'include' })
    
    // 清除本地存储的用户信息
    localStorage.removeItem('user')
    
    ElMessage.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
    // 即使后端调用失败，也要清除本地状态并跳转
    localStorage.removeItem('user')
    ElMessage.success('退出登录成功')
    router.push('/login')
  }
}

const handleChangePassword = () => {
  router.push('/teacher/change-password')
}
</script>

<style scoped>
.el-header {
  background-color: #1890ff;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left h1 {
  margin: 0;
  font-size: 20px;
}

.header-right {
  display: flex;
  align-items: center;
}
</style>